import Vue from 'vue'
import Vuex from 'vuex'
import { getToken, setToken } from '@/utils/auth'
import Storage from '@/utils/storage'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 当第一次获取的时候tokenObj为null  读取属性会报错  需要默认为空对象
    // JSON.parse(localStorage.getItem('HEIMA_TOUTIAO'))
    // storage.get('HEIMA_TOUTIAO_TOKEN')
    tokenObj: getToken() || {},
    user: {},
    keyList: Storage.get('TOUTIAO_KEY_LIST') || []
  },
  mutations: {
    // 存token
    SET_TOKEN(state, payload) {
      state.tokenObj = payload
      // 防止刷新丢失token 需要存放到本地存储
      // localStorage.setItem('HEIMA_TOUTIAO',JSON.stringify(payload))
      setToken(payload)
    },
    SET_USER(state, obj) {
      state.user = obj
    },
    // 存搜索历史
    SET_KEYLIST(state, val) {
      state.keyList.unshift(val)
      state.keyList = [...new Set(state.keyList)]
      Storage.set('TOUTIAO_KEY_LIST', state.keyList)
    },
    // 删除全部列表
    DEL_KEY_LIST(state) {
      state.keyList = []
      Storage.remove('TOUTIAO_KEY_LIST')
    },
    // 删除某一项
    DEL_INDEX(state, index) {
      state.keyList.splice(index, 1)
      Storage.set('TOUTIAO_KEY_LIST', state.keyList)
    }
  }
})
